#!/bin/bash
#
# chkconfig: - 86 14
# description: Fly agent daemom
# processname: fly-agent
# config: /opt/fly-agent/etc/agent.yml
#

export PATH=/usr/bin:/bin:/usr/sbin:/sbin

base=/opt/fly-agent
cd ${base}

mod=agent
binfile=fly-${mod}

usage()
{
	echo $"Usage: $0 {start|stop|restart|status}"
	exit 0
}

start()
{
	if [ ! -f ${binfile} ]; then
		echo "file[${binfile}] not found"
		exit 1
	fi

	result=$(pidof ${binfile})
	if [ "x${result}" != "x" ]; then
		echo "${mod} already started"
		return
	fi

	nohup /opt/fly-agent/${binfile} &> log/stdout.log &
	for((i=1;i<=15;i++)); do
		result=$(pidof ${binfile})
		if [ "x${result}" != "x" ]; then
			echo "${mod} started"
			return
		fi
		sleep 0.2
	done

	echo "cannot start ${mod}"
	exit 1
}

stop()
{
	result=$(pidof ${binfile})
	if [ "x${result}" = "x" ]; then
		echo "${mod} already stopped"
		return
	fi

	kill -9 $(pidof ${binfile})
	for((i=1;i<=15;i++)); do
		result=$(pidof ${binfile})
		if [ "x${result}" = "x" ]; then
			echo "${mod} stopped"
			return
		fi
		sleep 0.2
	done

	echo "cannot stop ${mod}"
	exit 1
}

restart()
{
	stop ${mod}
	start ${mod}
}

status()
{
	pid=$(pidof ${binfile})
	if [ "x${pid}" = "x" ]; then
		exit 1
	fi

	ps -f -p ${pid}
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	status)
		status
		;;
	*)
		usage
esac
